package link.jfire.socket.socketserver.interceptor.impl;

import link.jfire.baseutil.collection.ByteCache;
import link.jfire.baseutil.encrypt.AesUtil;
import link.jfire.socket.socketserver.bus.ServerChannelInfo;
import link.jfire.socket.socketserver.interceptor.EntryInterceptor;
import link.jfire.socket.socketserver.storage.Entry;

public class AESEncryptIntercepror implements EntryInterceptor
{
    
    @Override
    public int getOrder()
    {
        return 1;
    }
    
    @Override
    public int inInterceptor(Entry entry)
    {
        ServerChannelInfo channelInfo = entry.getServerChannelInfo();
        AesUtil aesUtil = new AesUtil(channelInfo.getKey());
        ByteCache businessData = entry.getBusinessData();
        byte[] result = aesUtil.decrypt(businessData.toArray());
        businessData.clear().putArray(result);
        return EntryInterceptor.next;
    }
    
    @Override
    public int outInterceptor(Entry entry)
    {
        ServerChannelInfo channelInfo = entry.getServerChannelInfo();
        ByteCache businessData = entry.getBusinessData();
        AesUtil aesUtil = new AesUtil(channelInfo.getKey());
        byte[] result = aesUtil.encrypt(businessData.toArray());
        businessData.clear().putArray(result);
        return EntryInterceptor.next;
    }
    
}
